package com.example.mydemo;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.mydemo.utils.FileUtil;
import com.google.gson.Gson;
import com.tal.pad.eye_protection.AwConDetectApi;
import com.tal.pad.eye_protection.ResultInfo;
import com.tal.pad.eye_protection.interfaces.NoPersonStatusCallback;
import com.tal.pad.eye_protection.interfaces.ProtectEyeResultCallback;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class ImageTestActivity extends AppCompatActivity {
    private final int MSG_STAR = 101;
    private final int MSG_STOP = 102;
    private final int MSG_SET_RESULT = 103;
    private final long TIME_WORK = 350L;
    private final long TIME_SLLEP = 1000L;
    private int starNum = 0;

    private List<File> files =new ArrayList<>();
    private ImageView iv_img;
    private TextView tv_result;
    private TextView tv_select_file_name;
    private Button btn_star;
    private String logFileName="log.txt";
//    private List<Map<String,String>> logs=new ArrayList<>();
    private StringBuffer sb=new StringBuffer();
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_STAR:
                    if (starNum < files.size()) {

                        Bitmap bitmap = FileUtil.fileToBitmap(files.get(starNum));
                        if (bitmap==null){
                            return;
                        }
                        iv_img.setImageBitmap(bitmap);
                        AwConDetectApi.getInstance().detectFrameTest(files.get(starNum).getAbsolutePath(),  "ID001");
//                        byte[] data = AssetsUtil.convertBitmapToNV21(bitmap);
//                        byte[] data= AiCoreImageUtil.bitmapToNv21(bitmap,bitmap.getWidth(),bitmap.getHeight());
//                        AwConDetectApi.getInstance().detectFrame(data, bitmap.getWidth(), bitmap.getHeight(), 0, 0, 1, "ID");

                        sendEmptyMessageDelayed(MSG_STOP, TIME_WORK);
                    }
                    break;
                case MSG_STOP:
                    AwConDetectApi.getInstance().getResult(new ProtectEyeResultCallback() {
                        @Override
                        public void onResult(ResultInfo resultInfo) {
                            AwConDetectApi.getInstance().resetResult();
                            Message msg0 =new  Message();
                            msg0.what=MSG_SET_RESULT;
                            msg0.obj=resultInfo;
                            sendMessage(msg0);
                        }
                    });
                    break;
                case MSG_SET_RESULT:
                    Map<String,String> map=new HashMap<>();
                    map.put(files.get(starNum).getName(),new Gson().toJson(msg.obj));
                    sb.append(new Gson().toJson(map)+"\n");
//                    logs.add(map);
                    String str = "当前文件名称:"+files.get(starNum).getName()+"\n当前进度："+(starNum+1)+"/"+files.size()+"\n" +"结果：" + new Gson().toJson(msg.obj);
                    tv_result.setText(str);
                    starNum++;
                    if (starNum < files.size()) {
                        sendEmptyMessageDelayed(MSG_STAR, TIME_SLLEP);
                    }else {
//                        String content=new Gson().toJson(logs);
//                        content=content.replace("[","");
//                        content=content.replace("]","");
//                        FileUtil.writeToTxt(logFileName,content);
                        FileUtil.writeToTxt(logFileName,sb.toString());
                    }
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_test);
        iv_img=findViewById(R.id.iv_img1);
        tv_result=findViewById(R.id.tv_result1);
        tv_select_file_name=findViewById(R.id.tv_select_file_name);
        btn_star=findViewById(R.id.btn_star);
        btn_star.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                start();
            }
        });

        start();
    }
    public void start() {
        Date currentDate = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒", Locale.getDefault());
        String formattedDate = dateFormat.format(currentDate);
        logFileName=formattedDate+".txt";
//        logs.clear();

        sb.setLength(0);
        files.clear();
        starNum=0;
        files.addAll(FileUtil.getAllFilesInTestFolder());
        tv_result.setText("");
        String fileNameStr="";
        for (int i = 0; i < files.size(); i++) {
            fileNameStr+=files.get(i).getName()+"\n";
        }
        tv_select_file_name.setText(fileNameStr);
        Log.e("+++", "onCreate: "+new Gson().toJson(files));
        handler.sendEmptyMessage(MSG_STAR);
    }
    public void getResult(View view) {

        AwConDetectApi.getInstance().getResult(new ProtectEyeResultCallback() {
            @Override
            public void onResult(ResultInfo resultInfo) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        tv_result.setText("结果：" + new Gson().toJson(resultInfo));
                    }
                }) ;
            }
        });
    }
    public void resetResult(View view){
        AwConDetectApi.getInstance().resetResult();
    }

    public void getNoPerson(View view){
        AwConDetectApi.getInstance().getNoPersonStatus(new NoPersonStatusCallback() {
            @Override
            public void onNoPersonStatus(int status) {
                Log.e("+++", "onNoPersonStatus: "+status );
            }
        });
    }
}